﻿using MarkDownFileSplitter.Htm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkDownFileSplitter.Pdf
{
    internal class PdfHeadingMarker
    {
        private RichTextBox m_richTextBox;
        private string m_outputMarkdownPath;
        private CatalogTreeHandler m_catalogTreeHandler;

        public PdfHeadingMarker(CatalogTreeHandler catalogTreeHandler)
        {
            m_catalogTreeHandler = catalogTreeHandler;
        }

        public void InitWidget(TableLayoutControlCollection controls)
        {
            m_richTextBox = new RichTextBox();
            m_richTextBox.Dock = DockStyle.Fill;
            m_richTextBox.ReadOnly = true;
            controls.Add(m_richTextBox, 1, 0);
        }

        public void ReadText(string filePath)
        {
            m_outputMarkdownPath = Path.ChangeExtension(filePath, ".md");
            //先检查Umi-OCR工具是否存在
            if (!File.Exists(GlobalSetting.Instance.UmiOCRPath))
            {
                MessageBox.Show("Umi-OCR工具不存在，请先配置");
                return;
            }
            var imgDir = Path.Combine(Path.GetDirectoryName(filePath), "imgs"+Path.GetFileNameWithoutExtension(filePath));
            if (Directory.Exists(imgDir) == false || new DirectoryInfo(imgDir).GetFiles().Length == 0)
            {
                Directory.CreateDirectory(imgDir);
                List<byte[]> imgs = Freeware.Pdf2Png.ConvertAllPages(File.OpenRead(filePath));

                for (int i = 0; i < imgs.Count; i++)
                {
                    Image bitmap = Image.FromStream(new MemoryStream(imgs[i]));
                    string imagePath = Path.Combine(imgDir, "image-" + (i + 1) + ".png");
                    bitmap.Save(imagePath);
                }
            }
            var imagePaths = new DirectoryInfo(imgDir).GetFiles("*.png");
            for (var i = 0; i < imagePaths.Length; i++)
            {
                string outputTxtFilePath = Path.ChangeExtension(imagePaths[i].FullName, ".txt");
                if(File.Exists(outputTxtFilePath) == false)
                {
                    UmiOCRUtils.RunUmiOCR(imagePaths[i].FullName, outputTxtFilePath);
                }
            }
            UmiOCRUtils.QuitUmiOCR();

            var textFiles = new DirectoryInfo(imgDir).GetFiles("*.txt");
            Dictionary<int, string> contents = new Dictionary<int, string>();
            for (var i = 0; i < textFiles.Length; i++)
            {
                var t =Path.GetFileNameWithoutExtension( textFiles[i].Name).Split('-')[1];
                var content = File.ReadAllText(textFiles[i].FullName);
                contents.Add(int.Parse(t), content);
            }
            StringBuilder stringBuilder = new StringBuilder();
            for(var i=0;i< imagePaths.Length; i++)
            {
                if (contents.ContainsKey(i + 1))
                {
                    stringBuilder.Append(contents[i+1]);
                    stringBuilder.AppendLine();
                }
            }
            this.m_richTextBox.Text = stringBuilder.ToString();
        }

        public void ApplyHeadingStyle(int headingLevel)
        {
            HtmSelectionObject selectionObject = new HtmSelectionObject(m_richTextBox.SelectedText, m_richTextBox.SelectionStart, m_richTextBox.SelectionStart + m_richTextBox.SelectionLength);
            switch (headingLevel)
            {
                case 1:
                    m_richTextBox.SelectionFont = new Font("宋体", 25, FontStyle.Bold);
                    m_catalogTreeHandler.HandleHeadingLevel1(selectionObject);
                    break;
                case 2:
                    m_richTextBox.SelectionFont = new Font("宋体", 20, FontStyle.Bold);
                    m_catalogTreeHandler.HandleHeadingLevel2(selectionObject);
                    break;
                case 3:
                    m_richTextBox.SelectionFont = new Font("宋体", 15, FontStyle.Bold);
                    m_catalogTreeHandler.HandleHeadingLevel3(selectionObject);
                    break;
                default:
                    m_richTextBox.SelectionFont = new Font("宋体", 10);
                    //TODO：缺少一个将标记错的标题变为正文的方法
                    break;
            }
        }

        public void ConvertToMarkdown()
        {
            //先将所有文本写入
            StringBuilder markdown = new StringBuilder();
            markdown.Append(m_richTextBox.Text);

            List<MarkInfo> markInfos = new List<MarkInfo>();
            foreach (TreeNode rootNode in m_catalogTreeHandler.RootNodes)
            {
                AddMark(rootNode, 1, markInfos);
            }
            //从后到前添加Markdown的井号
            markInfos.Sort((x, y) => y.Position.CompareTo(x.Position));
            foreach (MarkInfo markInfo in markInfos)
            {
                string mark = GetMark(markInfo.Level);
                markdown.Insert(markInfo.Position, Environment.NewLine + mark);//前面不换行的话#标记会无效
            }
            File.WriteAllText(m_outputMarkdownPath, markdown.ToString(), Encoding.UTF8);
            MessageBox.Show($"文件已成功保存为: {m_outputMarkdownPath}", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void AddMark(TreeNode node, int currentLevel, List<MarkInfo> markInfos)
        {
            HtmCatalogTreeItem catalogTreeItem = (HtmCatalogTreeItem)node.Tag;
            markInfos.Add(new MarkInfo(catalogTreeItem.StartIndex, currentLevel));
            foreach (TreeNode child in node.Nodes)
            {
                AddMark(child, currentLevel + 1, markInfos);
            }
        }

        private string GetMark(int level)
        {
            switch (level)
            {
                case 1:
                    return "# ";
                case 2:
                    return "## ";
                case 3:
                    return "### ";
            }
            return null;
        }
    }
}
